package com.example.demo.entity;

import com.example.demo.pojo.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
* 实现UserDetail接口
*
* */
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
//@JsonIgnoreProperties({"enabled","user","accountNonExpired", "accountNonLocked", "credentialsNonExpired", "authorities"})
public class LoginUser implements UserDetails {
    private Map<String,Object> user;
    private List<String> permissions;
    public LoginUser(Map<String,Object> user , List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }
//    @JSONField(serialize = false)
//    @JsonIgnoreProperties({"authorities"})
    @JsonIgnore
    private List<SimpleGrantedAuthority> authorities;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //减少操作次数
        if(authorities!=null){
            return authorities;
        }
//        for (String item:
//                permissions) {
//            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(item);
//            authorities.add(simpleGrantedAuthority);
//        }
        if(permissions!=null&&permissions.size()>0){
            authorities=permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.get("password").toString();
    }

    @Override
    public String getUsername() {
        return user.get("account").toString();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
